#!/bin/bash
# echo the call so we can see what's going on
echo "$0 $1 $2 $3 $4 $5 $6"

# Check syntax
if [ "$1" = "" ]; then
	echo "$0 called without filename for source of phase!"
	read -p "You should not continue here! Please hit Ctrl-C until you are out of the script!"
	exit 0
fi

if [ -e $1 ]; then
	echo "Your phase file $1 was found!"
else
	echo "Your phase file $1 was NOT found!"
	read -p "You should not continue here! Please hit Ctrl-C until you are out of the script!"
	exit
fi

if [ "$2" = "" ]; then
	echo "$0 called without number of phase in source file!"
	read -p "You should not continue here! Please hit Ctrl-C until you are out of the script!"
	exit 0
fi

# Does the phase have atoms?
natoms=`grep CRS$2 $1 | grep NATOM | awk '{print $3}'`
if [ "$natoms" == "0" ]; then
  echo "A problem occured while converting $1!"
  echo "We did not get any atoms! Possibly the CIF file needs to be modified to get rid of charge states, i.e. convert Bi0+ to Bi as _atom_site_type_symbol?"
  read -p "You should hit Ctrl-c here and check your CIF file."
  exit
elif [ "$natoms" == "" ]; then
  echo "No atoms found!"
  read -p "Hit ctrl-c and check some things..."
else
  echo "We read <$natoms> atoms from the EXP file $1."
fi

# Add the phase
echo "k p p r" > temp.txt
echo $1 >> temp.txt
echo $2 >> temp.txt
echo "x" >> temp.txt
echo "x" >> temp.txt
echo "x" >> temp.txt


expedt `cat GSAS_EXP` < temp.txt > out.txt

echo "Added phase number \verb=$2= from file \verb=$1= to EXP file.\newline" >> `cat GSAS_EXP`.tex
